<template>
  <div>
    <el-button
      v-show="$store.state.user.buttons.indexOf('btn.Trademark.add')!==-1"
      type="primary"
      icon="el-icon-plus"
      style="margin:10px 0"
      @click="dialogFormVisible=true"
    >添加</el-button>

    <!-- 表格 -->
    <el-table
      style="width: 100%"
      :data="data"
      border
    >
      <template slot="empty">
        <el-empty description="空" />
      </template>
      <el-table-column
        prop="prop"
        label="序号"
        width="80px"
        align="center"
        type="index"
      />
      <el-table-column
        label="品牌名称"
        width="width"
        prop="tmName"
      />
      <el-table-column
        prop="prop"
        label="品牌LOGO"
        width="width"
      >
        <template slot-scope="{row}">
          <img style="width:100px;height:100px;object-fit:contain" :src="row.logoUrl" alt="">
        </template>
      </el-table-column>
      <el-table-column
        prop="prop"
        label="操作"
        width="width"
      >
        <template slot-scope="{row}">
          <el-button type="warning" :disabled="$store.state.user.buttons.indexOf('btn.Trademark.update')===-1" icon="el-icon-edit" size="mini" @click="edit(row)">修改</el-button>
          <el-button type="danger" :disabled="$store.state.user.buttons.indexOf('btn.Trademark.remove')===-1" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器更改layout的顺序可以修改布局的位置,加入箭头可以让组件到最右侧,pager-count连续页码数 -->
    <el-pagination
      style="margin-top:20px;text-align:center"
      :current-page="page"
      :total="total"
      :page-size="5"
      :page-sizes="[5,10,15]"
      layout="prev,pager,next,jumper,->,sizes,total"
      @size-change="sizeChange"
      @current-change="curChange"
    />
    <!-- 添加的对话框 -->
    <el-dialog :title="form.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible" :close-on-click-modal="false">

      <!-- 展示表单元素 -->
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName" :label-width="formLabelWidth" required>
          <el-input v-model="form.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl" :label-width="formLabelWidth" required>
          <!-- 图片上传 -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="send">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from 'lodash'
export default {
  name: 'TradeMark',
  data() {
    // 自定义校验规则
    var tmName = (rule, value, callback) => {
    // value是输入进来的文本
    // rule是规则
    // callback是放行的函数
      if (value.length < 2 || value.length > 10) {
        // 弹出报错信息
        callback(new Error('品牌名称需要2-10位'))
      } else {
        callback()
      }
    }
    return {
      page: 1,
      limit: 5,
      data: [],
      total: 0,
      dialogFormVisible: false,
      formLabelWidth: '100px',
      form: {
        tmName: '',
        logoUrl: ''
      },
      rules: {
        // 品牌名称的验证规则
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          // 引入自定义校验规则
          { validator: tmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '需要品牌图片' }
        ]
      }
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData() {
      try {
        const res = await this.$api.tradeMark.product(this.page, this.limit)
        if (res.code === 200) {
          document.querySelector('.el-button--primary').scrollIntoView({
            behavior: 'smooth'
          })
          this.total = res.data.total
          this.data = res.data.records
        }
      } catch (error) {
        alert(error)
      }
    },
    sizeChange(e) {
      this.limit = e
      this.getData()
    },
    curChange(e) {
      this.page = e
      this.getData()
    },

    // 编辑
    edit(row) {
      // 必须要使用拓展运算符浅拷贝进去(要不然没有提交数据的时候也会改变表格的内容)
      this.form = { ...row }
      this.dialogFormVisible = true
    },
    // 关闭
    close() {
      this.dialogFormVisible = false
      if (this.form.id) {
        this.form = { tmName: '', logoUrl: '', id: '' }
      } else {
        this.form = { tmName: '', logoUrl: '' }
      }
      this.$refs.ruleForm.resetFields()
    },
    // 删除品牌
    del(e) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await this.$api.tradeMark.deleteSku(e.id)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加加修改
    send: debounce(function() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          try {
            const res = await this.$api.tradeMark.saveUpdatebaseTrademark(this.form)
            if (res.code === 200) {
              this.$message({
                message: '成功',
                type: 'success'
              })
              this.getData()
            }
            this.close()
            this.dialogFormVisible = false
          } catch (error) {
            alert(error)
          }
        } else {
          return false
        }
      })
    }, 500),
    // 图片上传成功的操作
    handleAvatarSuccess(res, file) {
      // res是上传成功以后返回的地址
      // flie返回的是上传成功后返回前端的数据
      this.form.logoUrl = res.data
    },

    // 图片上传前的操作
    beforeAvatarUpload(file) {
      const isJPG = file.type.indexOf('image') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('只能上传图片')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss">
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
